package com.share.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.exception.ServiceException;
import com.share.device.domain.PowerBank;
import com.share.device.mapper.PowerBankMapper;
import com.share.device.service.IPowerBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PowerBankServiceImpl extends ServiceImpl<PowerBankMapper, PowerBank> implements IPowerBankService {

    @Override
    public List<PowerBank> selectListPowerBank(PowerBank powerBank) {
        return baseMapper.selectListPowerBank(powerBank);
    }

    /**
     * 业务逻辑：需要判断powerBankNo是否存在，如果存在不进行添加
     */
    @Override
    public int savePowerBank(PowerBank powerBank) {
        Long count = baseMapper.selectCount(
                new LambdaQueryWrapper<PowerBank>()
                        .eq(PowerBank::getPowerBankNo, powerBank.getPowerBankNo())
        );
        // 判断powerBankNo是否存在
        if (count > 0) {
            throw new ServiceException("充电宝编号已经存在");
        }
        return baseMapper.insert(powerBank);
    }

    /**
     * 业务逻辑：需要判断status是0才进行修改（0：未投入 1：使用中 -1：故障）
     */
    @Override
    public int updatePowerBank(PowerBank powerBank) {
        PowerBank oldPowerBank = baseMapper.selectById(powerBank.getId());
        // 判断status是否为0
        if (oldPowerBank != null && "0".equals(oldPowerBank.getStatus())) {
            return baseMapper.updateById(powerBank);
        }
        return 0;
    }

    @Override
    public PowerBank getByPowerBankNo(String powerBankNo) {
        return baseMapper.selectOne(
                new LambdaQueryWrapper<PowerBank>()
                        .eq(PowerBank::getPowerBankNo, powerBankNo)
        );
    }

}
